﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace T4Ui.dal
{
    public class Table
    {

        public List<Column> Columns;
        public List<FKTable> FKTables;
        public string Name { get; set; }
        public string CleanName { get; set; }
        public string ClassName { get; set; }
        public List<string> PrimaryKey { get; set; }
        public string Schema { get; set; }
        public string QueryableName { get; set; }
        public bool IsUser { get; set; }

        public const string signName = "Name";
        public const string signIsUser = "IsUser";
        public const string signUpdateKey = "UpdateKey";


        private string updataKey;

        public string UpdateKey
        {
            get
            {
                string[] cols=PrimaryKey.ToArray();
                updataKey = string.Join(",", cols);
                return updataKey;
            }
            set
            {
                if (PrimaryKey == null)
                {
                    PrimaryKey = new List<string>();
                }
                PrimaryKey.Clear();
                if (!string.IsNullOrEmpty(value))
                {
                    updataKey = value;
                    string[] cols = updataKey.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string tmp in cols)
                    {
                        PrimaryKey.Add(tmp);
                    }
                }

            }
        }
        public bool HasLogicalDelete()
        {
            return this.Columns.Any(x => x.Name.ToLower() == "deleted" || x.Name.ToLower() == "isdeleted");
        }
        public Column DeleteColumn
        {
            get
            {
                Column result = null;
                if (this.Columns.Any(x => x.Name.ToLower() == "deleted"))
                    result = this.Columns.Single(x => x.Name.ToLower() == "deleted");
                if (this.Columns.Any(x => x.Name.ToLower() == "isdeleted"))
                    result = this.Columns.Single(x => x.Name.ToLower() == "isdeleted");
                return result;
            }
        }
        public Column PK
        {
            get
            {
                return this.Columns.SingleOrDefault(x => x.IsPK) ?? this.Columns[0];
            }
        }
        public Column Descriptor
        {
            get
            {
                if (this.Columns.Count == 1)
                {
                    return this.Columns[0];
                }
                else
                {
                    //get the first string column
                    Column result = null;
                    result = this.Columns.FirstOrDefault(x => x.SysType.ToLower().Trim() == "string");
                    if (result == null)
                        result = this.Columns[1];
                    return result;
                }
            }
        }
    }
}
